home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 2002 November / SGI Freeware 2002 November - Disc 1.iso / dist / fw_emacs-lisp-intro.idb / usr / freeware / info / emacs-lisp-intro.info-8.z / emacs-lisp-intro.info-8
Text File  |  2002-07-08  |  50KB  |  1,291 lines

  1. This is emacs-lisp-intro.info, produced by makeinfo version 4.0b from
  2. emacs-lisp-intro.texi.
  3.  
  4. INFO-DIR-SECTION Emacs
  5. START-INFO-DIR-ENTRY
  6. * Emacs Lisp Intro: (eintr).
  7.               A simple introduction to Emacs Lisp programming.
  8. END-INFO-DIR-ENTRY
  9.  
  10.    This is an introduction to `Programming in Emacs Lisp', for people
  11. who are not programmers.
  12.  
  13.    Edition 2.04, 2001 Dec 17
  14.  
  15.    Copyright (C) 1990, '91, '92, '93, '94, '95, '97, 2001 Free Software
  16. Foundation, Inc.
  17.  
  18.    Permission is granted to copy, distribute and/or modify this document
  19. under the terms of the GNU Free Documentation License, Version 1.1 or
  20. any later version published by the Free Software Foundation; with the
  21. Invariant Section being the Preface, with the Front-Cover Texts being
  22. no Front-Cover Texts, and with the Back-Cover Texts being no Back-Cover
  23. Texts.  A copy of the license is included in the section entitled "GNU
  24. Free Documentation License".
  25.  
  26. 
  27. File: emacs-lisp-intro.info,  Node: Inc Example altogether,  Prev: Inc Example parts,  Up: Incrementing Loop
  28.  
  29. Putting the function definition together
  30. ........................................
  31.  
  32.    We have created the parts for the function definition; now we need to
  33. put them together.
  34.  
  35.    First, the contents of the `while' expression:
  36.  
  37.      (while (<= row-number number-of-rows)   ; true-or-false-test
  38.        (setq total (+ total row-number))
  39.        (setq row-number (1+ row-number)))    ; incrementer
  40.  
  41.    Along with the `let' expression varlist, this very nearly completes
  42. the body of the function definition.  However, it requires one final
  43. element, the need for which is somewhat subtle.
  44.  
  45.    The final touch is to place the variable `total' on a line by itself
  46. after the `while' expression.  Otherwise, the value returned by the
  47. whole function is the value of the last expression that is evaluated in
  48. the body of the `let', and this is the value returned by the `while',
  49. which is always `nil'.
  50.  
  51.    This may not be evident at first sight.  It almost looks as if the
  52. incrementing expression is the last expression of the whole function.
  53. But that expression is part of the body of the `while'; it is the last
  54. element of the list that starts with the symbol `while'.  Moreover, the
  55. whole of the `while' loop is a list within the body of the `let'.
  56.  
  57.    In outline, the function will look like this:
  58.  
  59.      (defun NAME-OF-FUNCTION (ARGUMENT-LIST)
  60.        "DOCUMENTATION..."
  61.        (let (VARLIST)
  62.          (while (TRUE-OR-FALSE-TEST)
  63.            BODY-OF-WHILE... )
  64.          ... )                     ; Need final expression here.
  65.  
  66.    The result of evaluating the `let' is what is going to be returned
  67. by the `defun' since the `let' is not embedded within any containing
  68. list, except for the `defun' as a whole.  However, if the `while' is
  69. the last element of the `let' expression, the function will always
  70. return `nil'.  This is not what we want!  Instead, what we want is the
  71. value of the variable `total'.  This is returned by simply placing the
  72. symbol as the last element of the list starting with `let'.  It gets
  73. evaluated after the preceding elements of the list are evaluated, which
  74. means it gets evaluated after it has been assigned the correct value
  75. for the total.
  76.  
  77.    It may be easier to see this by printing the list starting with
  78. `let' all on one line.  This format makes it evident that the VARLIST
  79. and `while' expressions are the second and third elements of the list
  80. starting with `let', and the `total' is the last element:
  81.  
  82.      (let (VARLIST) (while (TRUE-OR-FALSE-TEST) BODY-OF-WHILE... ) total)
  83.  
  84.    Putting everything together, the `triangle' function definition
  85. looks like this:
  86.  
  87.      (defun triangle (number-of-rows)    ; Version with
  88.                                          ;   incrementing counter.
  89.        "Add up the number of pebbles in a triangle.
  90.      The first row has one pebble, the second row two pebbles,
  91.      the third row three pebbles, and so on.
  92.      The argument is NUMBER-OF-ROWS."
  93.        (let ((total 0)
  94.              (row-number 1))
  95.          (while (<= row-number number-of-rows)
  96.            (setq total (+ total row-number))
  97.            (setq row-number (1+ row-number)))
  98.          total))
  99.  
  100.    After you have installed `triangle' by evaluating the function, you
  101. can try it out.  Here are two examples:
  102.  
  103.      (triangle 4)
  104.      
  105.      (triangle 7)
  106.  
  107. The sum of the first four numbers is 10 and the sum of the first seven
  108. numbers is 28.
  109.  
  110. 
  111. File: emacs-lisp-intro.info,  Node: Decrementing Loop,  Prev: Incrementing Loop,  Up: while
  112.  
  113. Loop with a Decrementing Counter
  114. --------------------------------
  115.  
  116.    Another common way to write a `while' loop is to write the test so
  117. that it determines whether a counter is greater than zero.  So long as
  118. the counter is greater than zero, the loop is repeated.  But when the
  119. counter is equal to or less than zero, the loop is stopped.  For this
  120. to work, the counter has to start out greater than zero and then be
  121. made smaller and smaller by a form that is evaluated repeatedly.
  122.  
  123.    The test will be an expression such as `(> counter 0)' which returns
  124. `t' for true if the value of `counter' is greater than zero, and `nil'
  125. for false if the value of `counter' is equal to or less than zero.  The
  126. expression that makes the number smaller and smaller can be a simple
  127. `setq' such as `(setq counter (1- counter))', where `1-' is a built-in
  128. function in Emacs Lisp that subtracts 1 from its argument.
  129.  
  130.    The template for a decrementing `while' loop looks like this:
  131.  
  132.      (while (> counter 0)                    ; true-or-false-test
  133.        BODY...
  134.        (setq counter (1- counter)))          ; decrementer
  135.  
  136. * Menu:
  137.  
  138. * Decrementing Example::        More pebbles on the beach.
  139. * Dec Example parts::           The parts of the function definition.
  140. * Dec Example altogether::      Putting the function definition together.
  141.  
  142. 
  143. File: emacs-lisp-intro.info,  Node: Decrementing Example,  Next: Dec Example parts,  Prev: Decrementing Loop,  Up: Decrementing Loop
  144.  
  145. Example with decrementing counter
  146. .................................
  147.  
  148.    To illustrate a loop with a decrementing counter, we will rewrite the
  149. `triangle' function so the counter decreases to zero.
  150.  
  151.    This is the reverse of the earlier version of the function.  In this
  152. case, to find out how many pebbles are needed to make a triangle with 3
  153. rows, add the number of pebbles in the third row, 3, to the number in
  154. the preceding row, 2, and then add the total of those two rows to the
  155. row that precedes them, which is 1.
  156.  
  157.    Likewise, to find the number of pebbles in a triangle with 7 rows,
  158. add the number of pebbles in the seventh row, 7, to the number in the
  159. preceding row, which is 6, and then add the total of those two rows to
  160. the row that precedes them, which is 5, and so on.  As in the previous
  161. example, each addition only involves adding two numbers, the total of
  162. the rows already added up and the number of pebbles in the row that is
  163. being added to the total.  This process of adding two numbers is
  164. repeated again and again until there are no more pebbles to add.
  165.  
  166.    We know how many pebbles to start with: the number of pebbles in the
  167. last row is equal to the number of rows.  If the triangle has seven
  168. rows, the number of pebbles in the last row is 7.  Likewise, we know how
  169. many pebbles are in the preceding row: it is one less than the number in
  170. the row.
  171.  
  172. 
  173. File: emacs-lisp-intro.info,  Node: Dec Example parts,  Next: Dec Example altogether,  Prev: Decrementing Example,  Up: Decrementing Loop
  174.  
  175. The parts of the function definition
  176. ....................................
  177.  
  178.    We start with three variables: the total number of rows in the
  179. triangle; the number of pebbles in a row; and the total number of
  180. pebbles, which is what we want to calculate.  These variables can be
  181. named `number-of-rows', `number-of-pebbles-in-row', and `total',
  182. respectively.
  183.  
  184.    Both `total' and `number-of-pebbles-in-row' are used only inside the
  185. function and are declared with `let'.  The initial value of `total'
  186. should, of course, be zero.  However, the initial value of
  187. `number-of-pebbles-in-row' should be equal to the number of rows in the
  188. triangle, since the addition will start with the longest row.
  189.  
  190.    This means that the beginning of the `let' expression will look like
  191. this:
  192.  
  193.      (let ((total 0)
  194.            (number-of-pebbles-in-row number-of-rows))
  195.        BODY...)
  196.  
  197.    The total number of pebbles can be found by repeatedly adding the
  198. number of pebbles in a row to the total already found, that is, by
  199. repeatedly evaluating the following expression:
  200.  
  201.      (setq total (+ total number-of-pebbles-in-row))
  202.  
  203. After the `number-of-pebbles-in-row' is added to the `total', the
  204. `number-of-pebbles-in-row' should be decremented by one, since the next
  205. time the loop repeats, the preceding row will be added to the total.
  206.  
  207.    The number of pebbles in a preceding row is one less than the number
  208. of pebbles in a row, so the built-in Emacs Lisp function `1-' can be
  209. used to compute the number of pebbles in the preceding row.  This can be
  210. done with the following expression:
  211.  
  212.      (setq number-of-pebbles-in-row
  213.            (1- number-of-pebbles-in-row))
  214.  
  215.    Finally, we know that the `while' loop should stop making repeated
  216. additions when there are no pebbles in a row.  So the test for the
  217. `while' loop is simply:
  218.  
  219.      (while (> number-of-pebbles-in-row 0)
  220.  
  221. 
  222. File: emacs-lisp-intro.info,  Node: Dec Example altogether,  Prev: Dec Example parts,  Up: Decrementing Loop
  223.  
  224. Putting the function definition together
  225. ........................................
  226.  
  227.    We can put these expressions together to create a function definition
  228. that works.  However, on examination, we find that one of the local
  229. variables is unneeded!
  230.  
  231.    The function definition looks like this:
  232.  
  233.      ;;; First subtractive version.
  234.      (defun triangle (number-of-rows)
  235.        "Add up the number of pebbles in a triangle."
  236.        (let ((total 0)
  237.              (number-of-pebbles-in-row number-of-rows))
  238.          (while (> number-of-pebbles-in-row 0)
  239.            (setq total (+ total number-of-pebbles-in-row))
  240.            (setq number-of-pebbles-in-row
  241.                  (1- number-of-pebbles-in-row)))
  242.          total))
  243.  
  244.    As written, this function works.
  245.  
  246.    However, we do not need `number-of-pebbles-in-row'.
  247.  
  248.    When the `triangle' function is evaluated, the symbol
  249. `number-of-rows' will be bound to a number, giving it an initial value.
  250. That number can be changed in the body of the function as if it were a
  251. local variable, without any fear that such a change will effect the
  252. value of the variable outside of the function.  This is a very useful
  253. characteristic of Lisp; it means that the variable `number-of-rows' can
  254. be used anywhere in the function where `number-of-pebbles-in-row' is
  255. used.
  256.  
  257.    Here is a second version of the function written a bit more cleanly:
  258.  
  259.      (defun triangle (number)                ; Second version.
  260.        "Return sum of numbers 1 through NUMBER inclusive."
  261.        (let ((total 0))
  262.          (while (> number 0)
  263.            (setq total (+ total number))
  264.            (setq number (1- number)))
  265.          total))
  266.  
  267.    In brief, a properly written `while' loop will consist of three
  268. parts:
  269.  
  270.   1. A test that will return false after the loop has repeated itself
  271.      the correct number of times.
  272.  
  273.   2. An expression the evaluation of which will return the value desired
  274.      after being repeatedly evaluated.
  275.  
  276.   3. An expression to change the value passed to the true-or-false-test
  277.      so that the test returns false after the loop has repeated itself
  278.      the right number of times.
  279.  
  280. 
  281. File: emacs-lisp-intro.info,  Node: dolist dotimes,  Next: Recursion,  Prev: while,  Up: Loops & Recursion
  282.  
  283. Save your time: `dolist' and `dotimes'
  284. ======================================
  285.  
  286.    In addition to `while', both `dolist' and `dotimes' provide for
  287. looping.  Sometimes these are quicker to write than the equivalent
  288. `while' loop.  Both are Lisp macros.  (*Note Macros: (elisp)Macros. )
  289.  
  290.    `dolist' works like a `while' loop that `CDRs down a list':
  291. `dolist' automatically shortens the list each time it loops--takes the
  292. CDR of the list--and binds the CAR of each shorter version of the list
  293. to the first of its arguments.
  294.  
  295.    `dotimes' loops a specific number of time: you specify the number.
  296.  
  297. * Menu:
  298.  
  299. * dolist::
  300. * dotimes::
  301.  
  302. 
  303. File: emacs-lisp-intro.info,  Node: dolist,  Next: dotimes,  Prev: dolist dotimes,  Up: dolist dotimes
  304.  
  305. The `dolist' Macro
  306. ..................
  307.  
  308.    Suppose, for example, you want to reverse a list, so that "first"
  309. "second" "third" becomes "third" "second" "first".
  310.  
  311.    In practice, you would use the `reverse' function, like this:
  312.  
  313.      (setq animals '(gazelle giraffe lion tiger))
  314.      
  315.      (reverse animals)
  316.  
  317. Here is how you could reverse the list using a `while' loop:
  318.  
  319.      (setq animals '(gazelle giraffe lion tiger))
  320.      
  321.      (defun reverse-list-with-while (list)
  322.        "Using while, reverse the order of LIST."
  323.        (let (value)  ; make sure list starts empty
  324.          (while list
  325.            (setq value (cons (car list) value))
  326.            (setq list (cdr list)))
  327.          value))
  328.      
  329.      (reverse-list-with-while animals)
  330.  
  331. And here is how you could use the `dolist' macro:
  332.  
  333.      (setq animals '(gazelle giraffe lion tiger))
  334.      
  335.      (defun reverse-list-with-dolist (list)
  336.        "Using dolist, reverse the order of LIST."
  337.        (let (value)  ; make sure list starts empty
  338.          (dolist (element list value)
  339.            (setq value (cons element value)))))
  340.      
  341.      (reverse-list-with-dolist animals)
  342.  
  343. In Info, you can place your cursor after the closing parenthesis of
  344. each expression and type `C-x C-e'; in each case, you should see
  345.  
  346.      (tiger lion giraffe gazelle)
  347.  
  348. in the echo area.
  349.  
  350.    For this example, the existing `reverse' function is obviously best.
  351. The `while' loop is just like our first example (*note A `while' Loop
  352. and a List: Loop Example.).  The `while' first checks whether the list
  353. has elements; if so, it constructs a new list by adding the first
  354. element of the list to the existing list (which in the first iteration
  355. of the loop is `nil').  Since the second element is prepended in front
  356. of the first element, and the third element is prepended in front of
  357. the second element, the list is reversed.
  358.  
  359.    In the expression using a `while' loop, the `(setq list (cdr list))'
  360. expression shortens the list, so the `while' loop eventually stops.  In
  361. addition, it provides the `cons' expression with a new first element by
  362. creating a new and shorter list at each repetition of the loop.
  363.  
  364.    The `dolist' expression does very much the same as the `while'
  365. expression, except that the `dolist' macro does some of the work you
  366. have to do when writing a `while' expression.
  367.  
  368.    Like a `while' loop, a `dolist' loops.  What is different is that it
  369. automatically shortens the list each time it loops -- it `CDRs down the
  370. list' on its own -- and it automatically binds the CAR of each shorter
  371. version of the list to the first of its arguments.
  372.  
  373.    In the example, the CAR of each shorter version of the list is
  374. referred to using the symbol `element', the list itself is called
  375. `list', and the value returned is called `value'.  The remainder of the
  376. `dolist' expression is the body.
  377.  
  378.    The `dolist' expression binds the CAR of each shorter version of the
  379. list to `element' and then evaluates the body of the expression; and
  380. repeats the loop.  The result is returned in `value'.
  381.  
  382. 
  383. File: emacs-lisp-intro.info,  Node: dotimes,  Prev: dolist,  Up: dolist dotimes
  384.  
  385. The `dotimes' Macro
  386. ...................
  387.  
  388.    The `dotimes' macro is similar to `dolist', except that it loops a
  389. specific number of times.
  390.  
  391.    The first argument to `dotimes' is assigned the numbers 0, 1, 2 and
  392. so forth each time around the loop, and the value of the third argument
  393. is returned.  You need to provide the value of the second argument,
  394. which is how many times the macro loops.
  395.  
  396.    For example, the following binds the numbers from 0 up to, but not
  397. including, the number 3 to the first argument, NUMBER, and then
  398. constructs a list of the three numbers.  (The first number is 0, the
  399. second number is 1, and the third number is 2; this makes a total of
  400. three numbers in all, starting with zero as the first number.)
  401.  
  402.      (let (value)      ; otherwise a value is a void variable
  403.        (dotimes (number 3 value)
  404.          (setq value (cons number value))))
  405.      
  406.      => (2 1 0)
  407.  
  408. `dotimes' returns `value', so the way to use `dotimes' is to operate on
  409. some expression NUMBER number of times and then return the result,
  410. either as a list or an atom.
  411.  
  412.    Here is an example of a `defun' that uses `dotimes' to add up the
  413. number of pebbles in a triangle.
  414.  
  415.      (defun triangle-using-dotimes (number-of-rows)
  416.        "Using dotimes, add up the number of pebbles in a triangle."
  417.      (let ((total 0))  ; otherwise a total is a void variable
  418.        (dotimes (number number-of-rows total)
  419.          (setq total (+ total (1+ number))))))
  420.      
  421.      (triangle-using-dotimes 4)
  422.  
  423. 
  424. File: emacs-lisp-intro.info,  Node: Recursion,  Next: Looping exercise,  Prev: dolist dotimes,  Up: Loops & Recursion
  425.  
  426. Recursion
  427. =========
  428.  
  429.    A recursive function contains code that tells the Lisp interpreter to
  430. call a program that runs exactly like itself, but with slightly
  431. different arguments.  The code runs exactly the same because it has the
  432. same name.  However, even though it has the same name, it is not the
  433. same thread of execution.  It is different.  In the jargon, it is a
  434. different `instance'.
  435.  
  436.    Eventually, if the program is written correctly, the `slightly
  437. different arguments' will become sufficiently different from the first
  438. arguments that the final instance will stop.
  439.  
  440. * Menu:
  441.  
  442. * Building Robots::             Same model, different serial number ...
  443. * Recursive Definition Parts::  Walk until you stop ...
  444. * Recursion with list::         Using a list as the test whether to recurse.
  445. * Recursive triangle function::
  446. * Recursion with cond::
  447. * Recursive Patterns::          Often used templates.
  448. * No Deferment::                Don't store up work ...
  449. * No deferment solution::
  450.  
  451. 
  452. File: emacs-lisp-intro.info,  Node: Building Robots,  Next: Recursive Definition Parts,  Prev: Recursion,  Up: Recursion
  453.  
  454. Building Robots: Extending the Metaphor
  455. ---------------------------------------
  456.  
  457.    It is sometimes helpful to think of a running program as a robot that
  458. does a job.  In doing its job, a recursive function calls on a second
  459. robot to help it.  The second robot is identical to the first in every
  460. way, except that the second robot helps the first and has been passed
  461. different arguments than the first.
  462.  
  463.    In a recursive function, the second robot may call a third; and the
  464. third may call a fourth, and so on.  Each of these is a different
  465. entity; but all are clones.
  466.  
  467.    Since each robot has slightly different instructions--the arguments
  468. will differ from one robot to the next--the last robot should know when
  469. to stop.
  470.  
  471.    Let's expand on the metaphor in which a computer program is a robot.
  472.  
  473.    A function definition provides the blueprints for a robot.  When you
  474. install a function definition, that is, when you evaluate a `defun'
  475. special form, you install the necessary equipment to build robots.  It
  476. is as if you were in a factory, setting up an assembly line.  Robots
  477. with the same name are built according to the same blueprints.  So they
  478. have, as it were, the same `model number', but a different `serial
  479. number'.
  480.  
  481.    We often say that a recursive function `calls itself'.  What we mean
  482. is that the instructions in a recursive function cause the Lisp
  483. interpreter to run a different function that has the same name and does
  484. the same job as the first, but with different arguments.
  485.  
  486.    It is important that the arguments differ from one instance to the
  487. next; otherwise, the process will never stop.
  488.  
  489. 
  490. File: emacs-lisp-intro.info,  Node: Recursive Definition Parts,  Next: Recursion with list,  Prev: Building Robots,  Up: Recursion
  491.  
  492. The Parts of a Recursive Definition
  493. -----------------------------------
  494.  
  495.    A recursive function typically contains a conditional expression
  496. which has three parts:
  497.  
  498.   1. A true-or-false-test that determines whether the function is called
  499.      again, here called the "do-again-test".
  500.  
  501.   2. The name of the function.  When this name is called, a new
  502.      instance of the function--a new robot, as it were--is created and
  503.      told what to do.
  504.  
  505.   3. An expression that returns a different value each time the
  506.      function is called, here called the "next-step-expression".
  507.      Consequently, the argument (or arguments) passed to the new
  508.      instance of the function will be different from that passed to the
  509.      previous instance.  This causes the conditional expression, the
  510.      "do-again-test", to test false after the correct number of
  511.      repetitions.
  512.  
  513.    Recursive functions can be much simpler than any other kind of
  514. function.  Indeed, when people first start to use them, they often look
  515. so mysteriously simple as to be incomprehensible.  Like riding a
  516. bicycle, reading a recursive function definition takes a certain knack
  517. which is hard at first but then seems simple.
  518.  
  519.    There are several different common recursive patterns.  A very simple
  520. pattern looks like this:
  521.  
  522.      (defun NAME-OF-RECURSIVE-FUNCTION (ARGUMENT-LIST)
  523.        "DOCUMENTATION..."
  524.        (if DO-AGAIN-TEST
  525.          BODY...
  526.          (NAME-OF-RECURSIVE-FUNCTION
  527.               NEXT-STEP-EXPRESSION)))
  528.  
  529.    Each time a recursive function is evaluated, a new instance of it is
  530. created and told what to do.  The arguments tell the instance what to
  531. do.
  532.  
  533.    An argument is bound to the value of the next-step-expression.  Each
  534. instance runs with a different value of the next-step-expression.
  535.  
  536.    The value in the next-step-expression is used in the do-again-test.
  537.  
  538.    The value returned by the next-step-expression is passed to the new
  539. instance of the function, which evaluates it (or some
  540. transmogrification of it) to determine whether to continue or stop.
  541. The next-step-expression is designed so that the do-again-test returns
  542. false when the function should no longer be repeated.
  543.  
  544.    The do-again-test is sometimes called the "stop condition", since it
  545. stops the repetitions when it tests false.
  546.  
  547. 
  548. File: emacs-lisp-intro.info,  Node: Recursion with list,  Next: Recursive triangle function,  Prev: Recursive Definition Parts,  Up: Recursion
  549.  
  550. Recursion with a List
  551. ---------------------
  552.  
  553.    The example of a `while' loop that printed the elements of a list of
  554. numbers can be written recursively.  Here is the code, including an
  555. expression to set the value of the variable `animals' to a list.
  556.  
  557.    If you are using Emacs 20 or before, this example must be copied to
  558. the `*scratch*' buffer and each expression must be evaluated there.
  559. Use `C-u C-x C-e' to evaluate the `(print-elements-recursively
  560. animals)' expression so that the results are printed in the buffer;
  561. otherwise the Lisp interpreter will try to squeeze the results into the
  562. one line of the echo area.
  563.  
  564.    Also, place your cursor immediately after the last closing
  565. parenthesis of the `print-elements-recursively' function, before the
  566. comment.  Otherwise, the Lisp interpreter will try to evaluate the
  567. comment.
  568.  
  569.    If you are using Emacs 21 or later, you can evaluate this expression
  570. directly in Info.
  571.  
  572.      (setq animals '(gazelle giraffe lion tiger))
  573.      
  574.      (defun print-elements-recursively (list)
  575.        "Print each element of LIST on a line of its own.
  576.      Uses recursion."
  577.        (if list                              ; do-again-test
  578.            (progn
  579.              (print (car list))              ; body
  580.              (print-elements-recursively     ; recursive call
  581.               (cdr list)))))                 ; next-step-expression
  582.      
  583.      (print-elements-recursively animals)
  584.  
  585.    The `print-elements-recursively' function first tests whether there
  586. is any content in the list; if there is, the function prints the first
  587. element of the list, the CAR of the list.  Then the function `invokes
  588. itself', but gives itself as its argument, not the whole list, but the
  589. second and subsequent elements of the list, the CDR of the list.
  590.  
  591.    Put another way, if the list is not empty, the function invokes
  592. another instance of code that is similar to the initial code, but is a
  593. different thread of execution, with different arguments than the first
  594. instance.
  595.  
  596.    Put in yet another way, if the list is not empty, the first robot
  597. assemblies a second robot and tells it what to do; the second robot is
  598. a different individual from the first, but is the same model.
  599.  
  600.    When the second evaluation occurs, the `if' expression is evaluated
  601. and if true, prints the first element of the list it receives as its
  602. argument (which is the second element of the original list).  Then the
  603. function `calls itself' with the CDR of the list it is invoked with,
  604. which (the second time around) is the CDR of the CDR of the original
  605. list.
  606.  
  607.    Note that although we say that the function `calls itself', what we
  608. mean is that the Lisp interpreter assembles and instructs a new
  609. instance of the program.  The new instance is a clone of the first, but
  610. is a separate individual.
  611.  
  612.    Each time the function `invokes itself', it invokes itself on a
  613. shorter version of the original list.  It creates a new instance that
  614. works on a shorter list.
  615.  
  616.    Eventually, the function invokes itself on an empty list.  It creates
  617. a new instance whose argument is `nil'.  The conditional expression
  618. tests the value of `list'.  Since the value of `list' is `nil', the
  619. `if' expression tests false so the then-part is not evaluated.  The
  620. function as a whole then returns `nil'.
  621.  
  622.    When you evaluate `(print-elements-recursively animals)' in the
  623. `*scratch*' buffer, you see this result:
  624.  
  625.      giraffe
  626.      
  627.      gazelle
  628.      
  629.      lion
  630.      
  631.      tiger
  632.      nil
  633.  
  634. 
  635. File: emacs-lisp-intro.info,  Node: Recursive triangle function,  Next: Recursion with cond,  Prev: Recursion with list,  Up: Recursion
  636.  
  637. Recursion in Place of a Counter
  638. -------------------------------
  639.  
  640.    The `triangle' function described in a previous section can also be
  641. written recursively.  It looks like this:
  642.  
  643.      (defun triangle-recursively (number)
  644.        "Return the sum of the numbers 1 through NUMBER inclusive.
  645.      Uses recursion."
  646.        (if (= number 1)                    ; do-again-test
  647.            1                               ; then-part
  648.          (+ number                         ; else-part
  649.             (triangle-recursively          ; recursive call
  650.              (1- number)))))               ; next-step-expression
  651.      
  652.      (triangle-recursively 7)
  653.  
  654. You can install this function by evaluating it and then try it by
  655. evaluating `(triangle-recursively 7)'.  (Remember to put your cursor
  656. immediately after the last parenthesis of the function definition,
  657. before the comment.)  The function evaluates to 28.
  658.  
  659.    To understand how this function works, let's consider what happens
  660. in the various cases when the function is passed 1, 2, 3, or 4 as the
  661. value of its argument.
  662.  
  663. * Menu:
  664.  
  665. * Recursive Example arg of 1 or 2::
  666. * Recursive Example arg of 3 or 4::
  667.  
  668. 
  669. File: emacs-lisp-intro.info,  Node: Recursive Example arg of 1 or 2,  Next: Recursive Example arg of 3 or 4,  Prev: Recursive triangle function,  Up: Recursive triangle function
  670.  
  671. An argument of 1 or 2
  672. .....................
  673.  
  674.    First, what happens if the value of the argument is 1?
  675.  
  676.    The function has an `if' expression after the documentation string.
  677. It tests whether the value of `number' is equal to 1; if so, Emacs
  678. evaluates the then-part of the `if' expression, which returns the
  679. number 1 as the value of the function.  (A triangle with one row has
  680. one pebble in it.)
  681.  
  682.    Suppose, however, that the value of the argument is 2.  In this case,
  683. Emacs evaluates the else-part of the `if' expression.
  684.  
  685.    The else-part consists of an addition, the recursive call to
  686. `triangle-recursively' and a decrementing action; and it looks like
  687. this:
  688.  
  689.      (+ number (triangle-recursively (1- number)))
  690.  
  691.    When Emacs evaluates this expression, the innermost expression is
  692. evaluated first; then the other parts in sequence.  Here are the steps
  693. in detail:
  694.  
  695. Step 1    Evaluate the innermost expression.
  696.      The innermost expression is `(1- number)' so Emacs decrements the
  697.      value of `number' from 2 to 1.
  698.  
  699. Step 2    Evaluate the `triangle-recursively' function.
  700.      The Lisp interpreter creates an individual instance of
  701.      `triangle-recursively'.  It does not matter that this function is
  702.      contained within itself.  Emacs passes the result Step 1 as the
  703.      argument used by this instance of the `triangle-recursively'
  704.      function
  705.  
  706.      In this case, Emacs evaluates `triangle-recursively' with an
  707.      argument of 1.  This means that this evaluation of
  708.      `triangle-recursively' returns 1.
  709.  
  710. Step 3    Evaluate the value of `number'.
  711.      The variable `number' is the second element of the list that
  712.      starts with `+'; its value is 2.
  713.  
  714. Step 4    Evaluate the `+' expression.
  715.      The `+' expression receives two arguments, the first from the
  716.      evaluation of `number' (Step 3) and the second from the evaluation
  717.      of `triangle-recursively' (Step 2).
  718.  
  719.      The result of the addition is the sum of 2 plus 1, and the number
  720.      3 is returned, which is correct.  A triangle with two rows has
  721.      three pebbles in it.
  722.  
  723. 
  724. File: emacs-lisp-intro.info,  Node: Recursive Example arg of 3 or 4,  Prev: Recursive Example arg of 1 or 2,  Up: Recursive triangle function
  725.  
  726. An argument of 3 or 4
  727. .....................
  728.  
  729.    Suppose that `triangle-recursively' is called with an argument of 3.
  730.  
  731. Step 1    Evaluate the do-again-test.
  732.      The `if' expression is evaluated first.  This is the do-again test
  733.      and returns false, so the else-part of the `if' expression is
  734.      evaluated.  (Note that in this example, the do-again-test causes
  735.      the function to call itself when it tests false, not when it tests
  736.      true.)
  737.  
  738. Step 2    Evaluate the innermost expression of the else-part.
  739.      The innermost expression of the else-part is evaluated, which
  740.      decrements 3 to 2.  This is the next-step-expression.
  741.  
  742. Step 3    Evaluate the `triangle-recursively' function.
  743.      The number 2 is passed to the `triangle-recursively' function.
  744.  
  745.      We know what happens when Emacs evaluates `triangle-recursively'
  746.      with an argument of 2.  After going through the sequence of
  747.      actions described earlier, it returns a value of 3.  So that is
  748.      what will happen here.
  749.  
  750. Step 4    Evaluate the addition.
  751.      3 will be passed as an argument to the addition and will be added
  752.      to the number with which the function was called, which is 3.
  753.  
  754. The value returned by the function as a whole will be 6.
  755.  
  756.    Now that we know what will happen when `triangle-recursively' is
  757. called with an argument of 3, it is evident what will happen if it is
  758. called with an argument of 4:
  759.  
  760.      In the recursive call, the evaluation of
  761.  
  762.           (triangle-recursively (1- 4))
  763.  
  764.      will return the value of evaluating
  765.  
  766.           (triangle-recursively 3)
  767.  
  768.      which is 6 and this value will be added to 4 by the addition in the
  769.      third line.
  770.  
  771. The value returned by the function as a whole will be 10.
  772.  
  773.    Each time `triangle-recursively' is evaluated, it evaluates a
  774. version of itself--a different instance of itself--with a smaller
  775. argument, until the argument is small enough so that it does not
  776. evaluate itself.
  777.  
  778.    Note that this particular design for a recursive function requires
  779. that operations be deferred.
  780.  
  781.    Before `(triangle-recursively 7)' can calculate its answer, it must
  782. call `(triangle-recursively 6)'; and before `(triangle-recursively 6)'
  783. can calculate its answer, it must call `(triangle-recursively 5)'; and
  784. so on.  That is to say, the calculation that `(triangle-recursively 7)'
  785. makes must be deferred until `(triangle-recursively 6)' makes its
  786. calculation; and `(triangle-recursively 6)' must defer until
  787. `(triangle-recursively 5)' completes; and so on.
  788.  
  789.    If each of these instances of `triangle-recursively' are thought of
  790. as different robots, the first robot must wait for the second to
  791. complete its job, which must wait until the third completes, and so on.
  792.  
  793.    There is a way around this kind of waiting, which we will discuss in
  794. *Note Recursion without Deferments: No Deferment.
  795.  
  796. 
  797. File: emacs-lisp-intro.info,  Node: Recursion with cond,  Next: Recursive Patterns,  Prev: Recursive triangle function,  Up: Recursion
  798.  
  799. Recursion Example Using `cond'
  800. ------------------------------
  801.  
  802.    The version of `triangle-recursively' described earlier is written
  803. with the `if' special form.  It can also be written using another
  804. special form called `cond'.  The name of the special form `cond' is an
  805. abbreviation of the word `conditional'.
  806.  
  807.    Although the `cond' special form is not used as often in the Emacs
  808. Lisp sources as `if', it is used often enough to justify explaining it.
  809.  
  810.    The template for a `cond' expression looks like this:
  811.  
  812.      (cond
  813.       BODY...)
  814.  
  815. where the BODY is a series of lists.
  816.  
  817.    Written out more fully, the template looks like this:
  818.  
  819.      (cond
  820.       (FIRST-TRUE-OR-FALSE-TEST FIRST-CONSEQUENT)
  821.       (SECOND-TRUE-OR-FALSE-TEST SECOND-CONSEQUENT)
  822.       (THIRD-TRUE-OR-FALSE-TEST THIRD-CONSEQUENT)
  823.        ...)
  824.  
  825.    When the Lisp interpreter evaluates the `cond' expression, it
  826. evaluates the first element (the CAR or true-or-false-test) of the
  827. first expression in a series of expressions within the body of the
  828. `cond'.
  829.  
  830.    If the true-or-false-test returns `nil' the rest of that expression,
  831. the consequent, is skipped and  the true-or-false-test of the next
  832. expression is evaluated.  When an expression is found whose
  833. true-or-false-test returns a value that is not `nil', the consequent of
  834. that expression is evaluated.  The consequent can be one or more
  835. expressions.  If the consequent consists of more than one expression,
  836. the expressions are evaluated in sequence and the value of the last one
  837. is returned.  If the expression does not have a consequent, the value
  838. of the true-or-false-test is returned.
  839.  
  840.    If none of the true-or-false-tests test true, the `cond' expression
  841. returns `nil'.
  842.  
  843.    Written using `cond', the `triangle' function looks like this:
  844.  
  845.      (defun triangle-using-cond (number)
  846.        (cond ((<= number 0) 0)
  847.              ((= number 1) 1)
  848.              ((> number 1)
  849.               (+ number (triangle-using-cond (1- number))))))
  850.  
  851. In this example, the `cond' returns 0 if the number is less than or
  852. equal to 0, it returns 1 if the number is 1 and it evaluates `(+ number
  853. (triangle-using-cond (1- number)))' if the number is greater than 1.
  854.  
  855. 
  856. File: emacs-lisp-intro.info,  Node: Recursive Patterns,  Next: No Deferment,  Prev: Recursion with cond,  Up: Recursion
  857.  
  858. Recursive Patterns
  859. ------------------
  860.  
  861.    Here are three common recursive patterns.  Each involves a list.
  862. Recursion does not need to involve lists, but Lisp is designed for lists
  863. and this provides a sense of its primal capabilities.
  864.  
  865. * Menu:
  866.  
  867. * Every::
  868. * Accumulate::
  869. * Keep::
  870.  
  871. 
  872. File: emacs-lisp-intro.info,  Node: Every,  Next: Accumulate,  Prev: Recursive Patterns,  Up: Recursive Patterns
  873.  
  874. Recursive Pattern: _every_
  875. ..........................
  876.  
  877.    In the `every' recursive pattern, an action is performed on every
  878. element of a list.
  879.  
  880.    The basic pattern is:
  881.  
  882.    * If a list be empty, return `nil'.
  883.  
  884.    * Else, act on the beginning of the list (the CAR of the list)
  885.         -     through a recursive call by the function on the rest (the
  886.              CDR) of the list,
  887.  
  888.         -     and, optionally, combine the acted-on element, using
  889.           `cons',     with the results of acting on the rest.
  890.  
  891.    Here is example:
  892.  
  893.      (defun square-each (numbers-list)
  894.        "Square each of a NUMBERS LIST, recursively."
  895.        (if (not numbers-list)                ; do-again-test
  896.            nil
  897.          (cons
  898.           (* (car numbers-list) (car numbers-list))
  899.           (square-each (cdr numbers-list))))) ; next-step-expression
  900.      
  901.      (square-each '(1 2 3))
  902.          => (1 4 9)
  903.  
  904. If `numbers-list' is empty, do nothing.  But if it has content,
  905. construct a list combining the square of the first number in the list
  906. with the result of the recursive call.
  907.  
  908.    (The example follows the pattern exactly: `nil' is returned if the
  909. numbers' list is empty.  In practice, you would write the conditional
  910. so it carries out the action when the numbers' list is not empty.)
  911.  
  912.    The `print-elements-recursively' function (*note Recursion with a
  913. List: Recursion with list.) is another example of an `every' pattern,
  914. except in this case, rather than bring the results together using
  915. `cons', we print each element of output.
  916.  
  917.    The `print-elements-recursively' function looks like this:
  918.  
  919.      (setq animals '(gazelle giraffe lion tiger))
  920.      
  921.      (defun print-elements-recursively (list)
  922.        "Print each element of LIST on a line of its own.
  923.      Uses recursion."
  924.        (if list                              ; do-again-test
  925.            (progn
  926.              (print (car list))              ; body
  927.              (print-elements-recursively     ; recursive call
  928.               (cdr list)))))                 ; next-step-expression
  929.      
  930.      (print-elements-recursively animals)
  931.  
  932.    The pattern for `print-elements-recursively' is:
  933.  
  934.    * If the list be empty, do nothing.
  935.  
  936.    * But if the list has at least one element,
  937.         -     act on the beginning of the list (the CAR of the list),
  938.  
  939.         -     and make a recursive call on the rest (the CDR) of the
  940.           list.
  941.  
  942. 
  943. File: emacs-lisp-intro.info,  Node: Accumulate,  Next: Keep,  Prev: Every,  Up: Recursive Patterns
  944.  
  945. Recursive Pattern: _accumulate_
  946. ...............................
  947.  
  948.    Another recursive pattern is called the `accumulate' pattern.  In
  949. the `accumulate' recursive pattern, an action is performed on every
  950. element of a list and the result of that action is accumulated with the
  951. results of performing the action on the other elements.
  952.  
  953.    This is very like the `every' pattern using `cons', except that
  954. `cons' is not used, but some other combiner.
  955.  
  956.    The pattern is:
  957.  
  958.    * If a list be empty, return zero or some other constant.
  959.  
  960.    * Else, act on the beginning of the list (the CAR of the list),
  961.         -     and combine that acted-on element, using `+' or     some
  962.           other combining function, with
  963.  
  964.         -     a recursive call by the function on the rest (the CDR) of
  965.           the list.
  966.  
  967.    Here is an example:
  968.  
  969.      (defun add-elements (numbers-list)
  970.        "Add the elements of NUMBERS-LIST together."
  971.        (if (not numbers-list)
  972.            0
  973.          (+ (car numbers-list) (add-elements (cdr numbers-list)))))
  974.      
  975.      (add-elements '(1 2 3 4))
  976.          => 10
  977.  
  978.    *Note Making a List of Files: Files List, for an example of the
  979. accumulate pattern.
  980.  
  981. 
  982. File: emacs-lisp-intro.info,  Node: Keep,  Prev: Accumulate,  Up: Recursive Patterns
  983.  
  984. Recursive Pattern: _keep_
  985. .........................
  986.  
  987.    A third recursive pattern is called the `keep' pattern.  In the
  988. `keep' recursive pattern, each element of a list is tested; the element
  989. is acted on and the results are kept only if the element meets a
  990. criterion.
  991.  
  992.    Again, this is very like the `every' pattern, except the element is
  993. skipped unless it meets a criterion.
  994.  
  995.    The pattern has three parts:
  996.  
  997.    * If a list be empty, return `nil'.
  998.  
  999.    * Else, if the beginning of the list (the CAR of the list) passes
  1000.          a test
  1001.         -     act on that element and combine it, using `cons' with
  1002.  
  1003.         -     a recursive call by the function on the rest (the CDR) of
  1004.           the list.
  1005.  
  1006.    * Otherwise, if the beginning of the list (the CAR of the list) fails
  1007.      the test
  1008.         -     skip on that element,
  1009.  
  1010.         -     and, recursively call the function on the rest (the CDR)
  1011.           of the list.
  1012.  
  1013.    Here is an example that uses `cond':
  1014.  
  1015.      (defun keep-three-letter-words (word-list)
  1016.        "Keep three letter words in WORD-LIST."
  1017.        (cond
  1018.         ;; First do-again-test: stop-condition
  1019.         ((not word-list) nil)
  1020.      
  1021.         ;; Second do-again-test: when to act
  1022.         ((eq 3 (length (symbol-name (car word-list))))
  1023.          ;; combine acted-on element with recursive call on shorter list
  1024.          (cons (car word-list) (keep-three-letter-words (cdr word-list))))
  1025.      
  1026.         ;; Third do-again-test: when to skip element;
  1027.         ;;   recursively call shorter list with next-step expression
  1028.         (t  (keep-three-letter-words (cdr word-list)))))
  1029.      
  1030.      (keep-three-letter-words '(one two three four five six))
  1031.          => (one two six)
  1032.  
  1033.    It goes without saying that you need not use `nil' as the test for
  1034. when to stop; and you can, of course, combine these patterns.
  1035.  
  1036. 
  1037. File: emacs-lisp-intro.info,  Node: No Deferment,  Next: No deferment solution,  Prev: Recursive Patterns,  Up: Recursion
  1038.  
  1039. Recursion without Deferments
  1040. ----------------------------
  1041.  
  1042.    Let's consider again what happens with the `triangle-recursively'
  1043. function.  We will find that the intermediate calculations are deferred
  1044. until all can be done.
  1045.  
  1046.    Here is the function definition:
  1047.  
  1048.      (defun triangle-recursively (number)
  1049.        "Return the sum of the numbers 1 through NUMBER inclusive.
  1050.      Uses recursion."
  1051.        (if (= number 1)                    ; do-again-test
  1052.            1                               ; then-part
  1053.          (+ number                         ; else-part
  1054.             (triangle-recursively          ; recursive call
  1055.              (1- number)))))               ; next-step-expression
  1056.  
  1057.    What happens when we call this function with a argument of 7?
  1058.  
  1059.    The first instance of the `triangle-recursively' function adds the
  1060. number 7 to the value returned by a second instance of
  1061. `triangle-recursively', an instance that has been passed an argument of
  1062. 6.  That is to say, the first calculation is:
  1063.  
  1064.      (+ 7 (triangle-recursively 6)
  1065.  
  1066. The first instance of `triangle-recursively'--you may want to think of
  1067. it as a little robot--cannot complete its job.  It must hand off the
  1068. calculation for `(triangle-recursively 6)' to a second instance of the
  1069. program, to a second robot.  This second individual is completely
  1070. different from the first one; it is, in the jargon, a `different
  1071. instantiation'.  Or, put another way, it is a different robot.  It is
  1072. the same model as the first; it calculates triangle numbers
  1073. recursively; but it has a different serial number.
  1074.  
  1075.    And what does `(triangle-recursively 6)' return?  It returns the
  1076. number 6 added to the value returned by evaluating
  1077. `triangle-recursively' with an argument of 5.  Using the robot
  1078. metaphor, it asks yet another robot to help it.
  1079.  
  1080.    Now the total is:
  1081.  
  1082.      (+ 7 6 (triangle-recursively 5)
  1083.  
  1084.    And what happens next?
  1085.  
  1086.      (+ 7 6 5 (triangle-recursively 4)
  1087.  
  1088.    Each time `triangle-recursively' is called, except for the last
  1089. time, it creates another instance of the program--another robot--and
  1090. asks it to make a calculation.
  1091.  
  1092.    Eventually, the full addition is set up and performed:
  1093.  
  1094.      (+ 7 6 5 4 3 2 1)
  1095.  
  1096.    This design for the function defers the calculation of the first step
  1097. until the second can be done, and defers that until the third can be
  1098. done, and so on.  Each deferment means the computer must remember what
  1099. is being waited on.  This is not a problem when there are only a few
  1100. steps, as in this example.  But it can be a problem when there are more
  1101. steps.
  1102.  
  1103. 
  1104. File: emacs-lisp-intro.info,  Node: No deferment solution,  Prev: No Deferment,  Up: Recursion
  1105.  
  1106. No Deferment Solution
  1107. ---------------------
  1108.  
  1109.    The solution to the problem of deferred operations is to write in a
  1110. manner that does not defer operations(1).  This requires writing to a
  1111. different pattern, often one that involves writing two function
  1112. definitions, an `initialization' function and a `helper' function.
  1113.  
  1114.    The `initialization' function sets up the job; the `helper' function
  1115. does the work.
  1116.  
  1117.    Here are the two function definitions for adding up numbers.  They
  1118. are so simple, I find them hard to understand.
  1119.  
  1120.      (defun triangle-initialization (number)
  1121.        "Return the sum of the numbers 1 through NUMBER inclusive.
  1122.      This is the `initialization' component of a two function
  1123.      duo that uses recursion."
  1124.        (triangle-recursive-helper 0 0 number))
  1125.  
  1126.      (defun triangle-recursive-helper (sum counter number)
  1127.        "Return SUM, using COUNTER, through NUMBER inclusive.
  1128.      This is the `helper' component of a two function duo
  1129.      that uses recursion."
  1130.        (if (> counter number)
  1131.            sum
  1132.          (triangle-recursive-helper (+ sum counter)  ; sum
  1133.                                     (1+ counter)     ; counter
  1134.                                     number)))        ; number
  1135.  
  1136.    Install both function definitions by evaluating them, then call
  1137. `triangle-initialization' with 2 rows:
  1138.  
  1139.      (triangle-initialization 2)
  1140.          => 3
  1141.  
  1142.    The `initialization' function calls the first instance of the
  1143. `helper' function with three arguments: zero, zero, and a number which
  1144. is the number of rows in the triangle.
  1145.  
  1146.    The first two arguments passed to the `helper' function are
  1147. initialization values.  These values are changed when
  1148. `triangle-recursive-helper' invokes new instances.(2)
  1149.  
  1150.    Let's see what happens when we have a triangle that has one row.
  1151. (This triangle will have one pebble in it!)
  1152.  
  1153.    `triangle-initialization' will call its helper with the arguments
  1154. `0 0 1'.  That function will run the conditional test whether `(>
  1155. counter number)':
  1156.  
  1157.      (> 0 1)
  1158.  
  1159. and find that the result is false, so it will invoke the then-part of
  1160. the `if' clause:
  1161.  
  1162.          (triangle-recursive-helper
  1163.           (+ sum counter)  ; sum plus counter => sum
  1164.           (1+ counter)     ; increment counter => counter
  1165.           number)          ; number stays the same
  1166.  
  1167. which will first compute:
  1168.  
  1169.      (triangle-recursive-helper (+ 0 0)  ; sum
  1170.                                 (1+ 0)   ; counter
  1171.                                 1)       ; number
  1172. which is:
  1173.  
  1174.      (triangle-recursive-helper 0 1 1)
  1175.  
  1176.    Again, `(> counter number)' will be false, so again, the Lisp
  1177. interpreter will evaluate `triangle-recursive-helper', creating a new
  1178. instance with new arguments.
  1179.  
  1180.    This new instance will be;
  1181.  
  1182.          (triangle-recursive-helper
  1183.           (+ sum counter)  ; sum plus counter => sum
  1184.           (1+ counter)     ; increment counter => counter
  1185.           number)          ; number stays the same
  1186.      
  1187. which is:
  1188.  
  1189.      (triangle-recursive-helper 1 2 1)
  1190.  
  1191.    In this case, the `(> counter number)' test will be true!  So the
  1192. instance will return the value of the sum, which will be 1, as expected.
  1193.  
  1194.    Now, let's pass `triangle-initialization' an argument of 2, to find
  1195. out how many pebbles there are in a triangle with two rows.
  1196.  
  1197.    That function calls `(triangle-recursive-helper 0 0 2)'.
  1198.  
  1199.    In stages, the instances called will be:
  1200.  
  1201.                                sum counter number
  1202.      (triangle-recursive-helper 0    1       2)
  1203.      
  1204.      (triangle-recursive-helper 1    2       2)
  1205.      
  1206.      (triangle-recursive-helper 3    3       2)
  1207.  
  1208.    When the last instance is called, the `(> counter number)' test will
  1209. be true, so the instance will return the value of `sum', which will be
  1210. 3.
  1211.  
  1212.    This kind of pattern helps when you are writing functions that can
  1213. use many resources in a computer.
  1214.  
  1215.    ---------- Footnotes ----------
  1216.  
  1217.    (1) The phrase "tail recursive" is used to describe such a process,
  1218. one that uses `constant space'.
  1219.  
  1220.    (2) The jargon is mildly confusing:  `triangle-recursive-helper'
  1221. uses a process that is iterative in a procedure that is recursive.  The
  1222. process is called iterative because the computer need only record the
  1223. three values, `sum', `counter', and `number'; the procedure is
  1224. recursive because the function `calls itself'.  On the other hand, both
  1225. the process and the procedure used by `triangle-recursively' are called
  1226. recursive.  The word `recursive' has different meanings in the two
  1227. contexts.
  1228.  
  1229. 
  1230. File: emacs-lisp-intro.info,  Node: Looping exercise,  Prev: Recursion,  Up: Loops & Recursion
  1231.  
  1232. Looping Exercise
  1233. ================
  1234.  
  1235.    * Write a function similar to `triangle' in which each row has a
  1236.      value which is the square of the row number.  Use a `while' loop.
  1237.  
  1238.    * Write a function similar to `triangle' that multiplies instead of
  1239.      adds the values.
  1240.  
  1241.    * Rewrite these two functions recursively.  Rewrite these functions
  1242.      using `cond'.
  1243.  
  1244.    * Write a function for Texinfo mode that creates an index entry at
  1245.      the beginning of a paragraph for every `@dfn' within the paragraph.
  1246.      (In a Texinfo file, `@dfn' marks a definition.  For more
  1247.      information, see *Note Indicating Definitions:
  1248.      (texinfo)Indicating.)
  1249.  
  1250. 
  1251. File: emacs-lisp-intro.info,  Node: Regexp Search,  Next: Counting Words,  Prev: Loops & Recursion,  Up: Top
  1252.  
  1253. Regular Expression Searches
  1254. ***************************
  1255.  
  1256.    Regular expression searches are used extensively in GNU Emacs.  The
  1257. two functions, `forward-sentence' and `forward-paragraph', illustrate
  1258. these searches well.  They use regular expressions to find where to
  1259. move point.  The phrase `regular expression' is often written as
  1260. `regexp'.
  1261.  
  1262.    Regular expression searches are described in *Note Regular
  1263. Expression Search: (emacs)Regexp Search, as well as in *Note Regular
  1264. Expressions: (elisp)Regular Expressions.  In writing this chapter, I am
  1265. presuming that you have at least a mild acquaintance with them.  The
  1266. major point to remember is that regular expressions permit you to
  1267. search for patterns as well as for literal strings of characters.  For
  1268. example, the code in `forward-sentence' searches for the pattern of
  1269. possible characters that could mark the end of a sentence, and moves
  1270. point to that spot.
  1271.  
  1272.    Before looking at the code for the `forward-sentence' function, it
  1273. is worth considering what the pattern that marks the end of a sentence
  1274. must be.  The pattern is discussed in the next section; following that
  1275. is a description of the regular expression search function,
  1276. `re-search-forward'.  The `forward-sentence' function is described in
  1277. the section following.  Finally, the `forward-paragraph' function is
  1278. described in the last section of this chapter.  `forward-paragraph' is
  1279. a complex function that introduces several new features.
  1280.  
  1281. * Menu:
  1282.  
  1283. * sentence-end::                The regular expression for `sentence-end'.
  1284. * re-search-forward::           Very similar to `search-forward'.
  1285. * forward-sentence::            A straightforward example of regexp search.
  1286. * forward-paragraph::           A somewhat complex example.
  1287. * etags::                       How to create your own `TAGS' table.
  1288. * Regexp Review::
  1289. * re-search Exercises::
  1290.  
  1291.